'use strict';

const Controller = require('egg').Controller;
const UUID = require('uuid');
const { Op } = require('sequelize');

function toInt (str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class DemoController extends Controller {

  async list () {
    const ctx = this.ctx;
    const pageSize = !ctx.query.pageSize ? 10 : ctx.query.pageSize;
    const query = {
      limit: toInt(pageSize),
      offset: (toInt(!ctx.query.p ? 0 : ctx.query.p) - 1) * toInt(pageSize),
      order: [],
    };
    // console.debug('................这里是查询.........', query);
    const searchObject = {
      id: { type: 'string', required: false },
      name: { type: 'string', required: false },
      region: { type: 'string', required: false },
      start: { type: 'dateTime', required: false },
      end: { type: 'dateTime', required: false },
      orderBy: { type: 'string', require: false },
    };
    // 校验参数
    // ctx.validate(searchObject)
    // 组装参数
    ctx.status = 200;
    const search = Object.assign(ctx.query, { searchObject });

    const where = [];
    if (!search.id === false) {
      where.push({ id: { [Op.eq]: ('' + search.id.trim() + '') } });
    }
    if (!search.name === false) {
      where.push({ name: { [Op.like]: ('%' + search.name.trim() + '%') } });
    }
    if (!search.region === false) {
      where.push({ region: { [Op.like]: ('%' + search.region.trim() + '%') } });
    }
    if (!search.start === false) {
      where.push({ date1: { [Op.gte]: search.start.trim() } });
    }
    if (!search.end === false) {
      where.push({ date1: { [Op.lte]: search.end.trim() } });
    }
    query.where = { [Op.and]: where };
    if (!search.orderBy === false) {
      query.order = search.orderBy.split(',').map(x => x.split(/\s+/)).filter(x => !(x.length === 1 && x[0] === ''));
    }
    const { count, rows } = await ctx.model.Demo.findAndCountAll(query);

    ctx.body = { code: 20000, list: rows, total: count };
  }

  async createOrUpdate () {
    const { ctx, service } = this;
    const tempObject = {
      id: { type: 'string', required: false },
      name: { type: 'string' },
      content: { type: 'string', required: false },
      region: { type: 'string', required: false },
      imgs: { type: 'string', required: false },
      date1: { type: 'string', required: false },
      date2: { type: 'string', required: true },
      delivery: { type: 'string', required: false },
      classify: { type: 'string', required: false },
      resource: { type: 'string', required: false },
      remarks: { type: 'string', required: false },
    };
    // 校验参数
    // ctx.validate(tempObject)
    // 组装参数
    const req = Object.assign(ctx.request.body, { tempObject });

    console.debug('.....获得上传内容.(修改前)....', JSON.stringify(req, null, 4))
    req.delivery = !!((req.delivery === '1' || req.delivery === 'true'));
    req.date1 = (req.date1.replace(/(\d{4}\-\d\d\-\d\d)\s(\d\d:\d\d:\d\d)/g, '$1T$2.000Z'));
    req.date2 = (req.date2.replace(/(\d{4}\-\d\d\-\d\d)\s(\d\d:\d\d:\d\d)/g, '$1T$2.000Z'));
    let res = {};

    // 调用 Service 进行业务处理
    if (!ctx.request.body.id) {
      req.id = UUID.v4();
    }
    const contentText = req.resource.toString()

    console.debug('.....获得文章内容是.....', contentText)

    req.resource = ''

    console.debug('.....获得上传内容.....', JSON.stringify(req, null, 4))

    // 调用 Service 进行业务处理
    if (!ctx.request.body.id) {
      res = await ctx.model.Demo.create(req);
    } else {
      const demo = await ctx.model.Demo.findByPk(req.id);
      if (!demo) {
        // ctx.status = 404;
        ctx.status = 200;
        ctx.body = { code: 20000, rId: null };
        return;
      }
      res = await demo.update(req);
    }
    // 设置响应内容和响应状态码
    ctx.status = 200;
    ctx.body = { code: 20000, rId: res.id };
  }

  async index () {
    const ctx = this.ctx;
    const query = {
      limit: toInt(ctx.query.limit),
      offset: toInt(ctx.query.offset),
    };
    ctx.body = await ctx.model.Demo.findAll(query);
  }

  async show () {
    const ctx = this.ctx;
    ctx.body = await ctx.model.Demo.findByPk(toInt(ctx.params.id));
  }

  async create () {
    const ctx = this.ctx;
    const { name, age } = ctx.request.body;
    const Demo = await ctx.model.Demo.create({ name, age });
    ctx.status = 200;
    ctx.body = Demo;
  }

  async update () {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const Demo = await ctx.model.Demo.findByPk(id);
    if (!Demo) {
      ctx.status = 404;
      return;
    }

    const { name, age } = ctx.request.body;
    await Demo.update({ name, age });
    ctx.body = Demo;
  }

  async destroy () {
    const ctx = this.ctx;
    const demo = await ctx.model.Demo.findByPk(ctx.request.body.id);
    console.debug(ctx.params.id, '....demo.....', demo);
    if (!demo) {
      ctx.status = 200;
      ctx.body = { code: 20000, rId: null };
      return;
    }
    const result = await demo.destroy();
    ctx.status = 200;
    ctx.body = { code: 20000, deletedCount: typeof result.dataValues.id !== 'undefined' ? 1 : 0 };
  }
}

module.exports = DemoController;
